package com.zekdot.registerclient.dao;

import com.zekdot.registerclient.entity.EnrollMetaEntity;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Create by zekdot on 20-3-21.
 */
@Mapper
@Repository
public interface EnrollMetaDao {
    /**
     * 存储一个报名数据实体
     * @param enrollMetaEntity
     * @return
     */
    public int save(EnrollMetaEntity enrollMetaEntity);

    /**
     * 根据id获取报名实体
     * @param id 报名id
     * @return
     */
    @Select("SELECT * FROM enroll_meta WHERE id=#{id}")
    EnrollMetaEntity get(@Param("id") String id);

    /**
     * 更新报名状态
     * @param id 报名id
     * @param status 报名状态
     * @return
     */
    @Update("UPDATE enroll_meta SET status=#{status} WHERE id=#{id}")
    int updateStatus(@Param("id") String id,@Param("status") int status);

    /**
     * 获取更多的报名实体
     * @param userId 用户名
     * @param lastTime 最后一条的时间
     * @param length 长度
     * @return
     */
    @Select("SELECT id,title,start_time,end_time,status FROM enroll_meta WHERE host=#{userId} AND " +
            "start_time<#{lastTime} ORDER BY start_time DESC LIMIT #{length}")
    List<EnrollMetaEntity> getMoreEnrollMeta(@Param("userId") String userId, @Param("lastTime") Date lastTime,
                                             @Param("length") int length);

    /**
     * 获取报名元数据描述
     * @param username 用户名
     * @param eId 报名id
     * @param joinMet 加入方式
     * @return
     */
    @Select("SELECT m.title,m.checked,m.end_method endMethod,m.enroll_limit enrollLimit,m.num_limit numLimit,m.plan_end_time planEndTime,\n" +
            "            m.start_time startTime,m.status,t.token FROM enroll_meta m LEFT JOIN enroll_token t ON m.id=t.e_id\n" +
            "            WHERE m.id=#{eId} AND (m.host=#{username} OR (m.enroll_limit & 1=1 AND #{joinMet}=1))")
    Map<String,Object> getMetaDesc(@Param("username")String username, @Param("eId")String eId, @Param("joinMet")int joinMet);

    /**
     * 根据用户名获取密码
     * @param userId
     * @return
     */
    @Select("SELECT password FROM user WHERE username=#{userId}")
    String getPassword(@Param("userId") String userId);

    /**
     * 插入令牌
     * @param eId 报名id
     * @param token 令牌值
     * @return
     */
    @Insert("INSERT INTO enroll_token VALUES(#{eId},#{token})")
    int saveToken(@Param("eId") String eId,@Param("token") String token);

    /**
     * 删除报名元数据
     * @param eId 报名id
     * @return
     */
    @Delete("DELETE FROM enroll_meta WHERE id=#{eId}")
    int deleteMeta(@Param("eId")String eId);

    /**
     * 获取重用的报名元数据部分
     * @param eId 报名id
     * @return
     */
    @Select("SELECT title,content,checked,enroll_limit enrollLimit,end_method endMethod,num_limit numLimit," +
            "plan_end_time planEndTime,status_tip statuTip FROM enroll_meta WHERE id=#{eId}")
    Map<String,Object> reuseMetaData(@Param("eId")String eId);
}
